package com.weiyi.biz.service;

import com.alibaba.fastjson.JSONObject;
import com.weiyi.biz.domain.WeiyiLog;
import com.weiyi.biz.dto.EquipInfo;
import com.weiyi.biz.mapper.WyManageMapper;
import org.apache.commons.codec.binary.Base64;
import org.apache.qpid.jms.JmsConnection;
import org.apache.qpid.jms.JmsConnectionListener;
import org.apache.qpid.jms.message.JmsInboundMessageDispatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import java.net.URI;
import java.util.Date;
import java.util.Hashtable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @version 1.0
 * @ClassName AmqpJavaClientDemo  位移传感器订阅获取数据
 * @Description TODO
 * @Author xiaoq
 * @Date 2020/8/28 9:32
 **/
@Component
@Order(99)
public class AliyunAmqpListen implements ApplicationRunner {

    private static final Logger logger = LoggerFactory.getLogger(AliyunAmqpListen.class);
    @Autowired
    private IWeiyiLogService weiyiLogService;
    @Autowired
    WyManageMapper wyManageMapper;


    @Value(value = "${aliyun.accessKey}")
    private String accessKey;

    @Value(value = "${aliyun.accessSecret}")
    private String accessSecret;

    @Value(value = "${aliyun.consumerGroupId}")
    private String consumerGroupId;

    @Value(value = "${aliyun.clientId}")
    private String clientId;

    @Value(value = "${aliyun.connectionUrl}")
    private String connectionUrl;

    @Value(value = "${aliyun.subTopic}")
    private  String subTopic;


    //业务处理异步线程池
    private final static ExecutorService executorService = new ThreadPoolExecutor(
            Runtime.getRuntime().availableProcessors(),
            Runtime.getRuntime().availableProcessors() * 2, 60, TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(50000));


    @Override
    public void run(ApplicationArguments args) throws Exception {

        logger.info("位移传感器开始监听---------------------");

        //参数说明，请参见AMQP客户端接入说明文档。
        long timeStamp = System.currentTimeMillis();
        //签名方法：支持hmacmd5、hmacsha1和hmacsha256。
        String signMethod = "hmacsha1";

        //UserName组装方法，请参见上一篇文档：AMQP客户端接入说明。
        String userName = clientId + "|authMode=aksign"
                + ",signMethod=" + signMethod
                + ",timestamp=" + timeStamp
                + ",authId=" + accessKey
                + ",consumerGroupId=" + consumerGroupId
                + "|";
        //password组装方法，请参见上一篇文档：AMQP客户端接入说明。
        String signContent = "authId=" + accessKey + "&timestamp=" + timeStamp;
        String password = doSign(signContent, accessSecret, signMethod);

        Hashtable<String, String> hashtable = new Hashtable<>();
        hashtable.put("connectionfactory.SBCF", connectionUrl);
        hashtable.put("queue.QUEUE", "default");
        hashtable.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jms.jndi.JmsInitialContextFactory");
        Context context = new InitialContext(hashtable);
        ConnectionFactory cf = (ConnectionFactory) context.lookup("SBCF");
        Destination queue = (Destination) context.lookup("QUEUE");
        // Create Connection
        Connection connection = cf.createConnection(userName, password);
        ((JmsConnection) connection).addConnectionListener(myJmsConnectionListener);
        // Session.AUTO_ACKNOWLEDGE: SDK自动ACK（推荐）
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        connection.start();
        // Create Receiver Link
        MessageConsumer consumer = session.createConsumer(queue);
        consumer.setMessageListener(messageListener);

    }


    private  MessageListener messageListener = new MessageListener() {
        @Override
        public void onMessage(Message message) {
            try {
                executorService.submit(() -> processMessage(message));
            } catch (Exception e) {
                logger.error("submit task occurs exception ", e);
            }
        }
    };


    private  JmsConnectionListener myJmsConnectionListener = new JmsConnectionListener() {
        /**
         * 连接成功建立。
         */
        @Override
        public void onConnectionEstablished(URI remoteURI) {
            logger.info("onConnectionEstablished, remoteUri:{}", remoteURI);
        }

        /**
         * 尝试过最大重试次数之后，最终连接失败。
         */
        @Override
        public void onConnectionFailure(Throwable error) {
            logger.error("onConnectionFailure, {}", error.getMessage());
        }

        /**
         * 连接中断。
         */
        @Override
        public void onConnectionInterrupted(URI remoteURI) {
            logger.info("onConnectionInterrupted, remoteUri:{}", remoteURI);
        }

        /**
         * 连接中断后又自动重连上。
         */
        @Override
        public void onConnectionRestored(URI remoteURI) {
            logger.info("onConnectionRestored, remoteUri:{}", remoteURI);
        }

        @Override
        public void onInboundMessage(JmsInboundMessageDispatch envelope) {
        }

        @Override
        public void onSessionClosed(Session session, Throwable cause) {
        }

        @Override
        public void onConsumerClosed(MessageConsumer consumer, Throwable cause) {
        }

        @Override
        public void onProducerClosed(MessageProducer producer, Throwable cause) {
        }
    };

    /**
     * 计算签名，password组装方法，请参见AMQP客户端接入说明文档。
     */
    private String doSign(String toSignString, String secret, String signMethod) throws Exception {
        SecretKeySpec signingKey = new SecretKeySpec(secret.getBytes(), signMethod);
        Mac mac = Mac.getInstance(signMethod);
        mac.init(signingKey);
        byte[] rawHmac = mac.doFinal(toSignString.getBytes());
        return Base64.encodeBase64String(rawHmac);
    }


    /**
     * 在这里处理您收到消息后的具体业务逻辑。
     */
    private  void processMessage(Message message) {
        try {
            logger.info("receive aliyun data--当前线程：{}",Thread.currentThread().getId());

            byte[] body = message.getBody(byte[].class);
            String content = new String(body);
            String topic = message.getStringProperty("topic");
            String messageId = message.getStringProperty("messageId");
            logger.info("receive message"
                    + ", topic = " + topic
                    + ", messageId = " + messageId
                    + ", content = " + content);

            if (topic.contains(subTopic)){
                logger.info("解析到订阅主题{}",subTopic);
                JSONObject obj = JSONObject.parseObject(content);
                Long battery_val=obj.getLong("BATTERY_VAL");
                Long read_err_num=obj.getLong("READ_ERR_NUM");
                String id=obj.getString("ID");
                Long adc_value=obj.getLong("ADC_VALUE");
                Long offset_mm=obj.getLong("OFFSET_MM");
                Long orientation=obj.getLong("ORIENTATION");

                ///(str.split("/")[2])
                String code=topic.split("/")[2];
                EquipInfo e=wyManageMapper.selectWyEquipByCode(code);

                WeiyiLog log=new WeiyiLog();
                log.setDeviceId(e.getId());
                log.setBatteryVal(battery_val);
                log.setReadErrNum(read_err_num);
                log.setIdValue(id);
                log.setAdcValue(adc_value);
                log.setOffsetMm(offset_mm);
                log.setOrientation(orientation);
                log.setOperateTime(new Date());

                weiyiLogService.insertWeiyiLog(log);
            }

        } catch (Exception e) {
            logger.error("processMessage occurs error ", e);
        }
    }
}
